<?php 
class Userrelatedself extends CS_Controller
{
    public function _init()
    {
        $this->load->helper(array('common'));
        $this->load->library('pagination');
        $this->load->model('user_related_self_model', 'user_related_self');
        $this->load->model('user_type_model', 'user_type');
        $this->load->model('user_model', 'user');
        $this->load->model('operate_power_log_model', 'operate_power_log');
    }
    
    public function grid($pg = 1)
    {
        $page_num = 20;
        $num = ($pg-1)*$page_num;
        $config['first_url'] = base_url('userrelatedself/grid').$this->pageGetParam($this->input->get());
        $config['suffix'] = $this->pageGetParam($this->input->get());
        $config['base_url'] = base_url('userrelatedself/grid');
        $config['total_rows'] = $this->user_related_self->total($this->input->get());
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['page_list'] = $this->user_related_self->page_list($page_num, $num, $this->input->get());
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $this->load->view('userrelatedself/grid', $data);
    }
    
    public function add()
    {
        $data = array();
        $this->load->view('userrelatedself/add', $data);
    }
    
    public function addPost()
    {
        if ($this->validateParam($this->input->post('provider_uid'))) {
            $this->error('userrelatedself/add', '', '所属广告位不能为空');
        }
        if ($this->validateParam($this->input->post('reseller_uid'))) {
            $this->error('userrelatedself/add', '', '标题不能为空');
        }
        $providerRepeat = $this->user_related_self->providerUidRepeat($this->input->post('provider_uid',true));
        if($providerRepeat->num_rows() >0){
            $this->error('userrelatedself/grid', '', '该供应商对应分销商已经存在');
        }
        $this->db->trans_start();
        $resultId = $this->user_related_self->insertUserRelatedSelf($this->input->post());
        $this->db->trans_complete();
        if ($resultId) {
            $this->success('userrelatedself/grid', '', '保存成功！');
        } else {
            $this->error('userrelatedself/add', '', '保存失败！');
        }
    }
    
    public function edit($id)
    {
        $result = $this->user_related_self->findById($id);
        if($result->num_rows() <= 0) {
            $this->error('userrelatedself/grid', '', '该供应商信息不存在');
        }
        $data['userrelatedself'] = $result->row();
        $this->load->view('userrelatedself/edit', $data);
    }
    
    public function delete($id){
    	
        $this->db->trans_start();
        $this->user_related_self->delete($id);
        $this->provider_poundage_profit->deleteByRelatedId($id);
        $this->db->trans_complete();
        if($this->db->trans_status()===TRUE){
            $this->success('userrelatedself/grid', '', '删除成功！');
        } else {
            $this->error('userrelatedself/grid', '', '删除失败！');
        }
    }
    
    public function editPost()
    {
        $userrelatedself_id = $this->input->post('id');
        if ($this->validateParam($userrelatedself_id)) {
            $this->error('userrelatedself/grid', '', '编辑有误');
        }
        if ($this->validateParam($this->input->post('provider_uid'))) {
            $this->error('userrelatedself/edit', $userrelatedself_id, '所属广告位不能为空');
        }
        if ($this->validateParam($this->input->post('reseller_uid'))) {
            $this->error('userrelatedself/edit', $userrelatedself_id, '标题不能为空');
        }
        $this->db->trans_start();
        $resultId = $this->user_related_self->updateUserRelatedSelf($this->input->post());
        $this->db->trans_complete();
    
        if ($resultId) {
            $this->success('userrelatedself/grid', '', '保存成功！');
        } else {
            $this->error('userrelatedself/edit', $userrelatedself_id, '保存失败！');
        }
    }
    
    public function toggle()
    {
        $id = $this->input->post('id');
        $status = $this->input->post('flag');
        switch ($status) {
            case '1': $flag = '2'; break;
            case '2': $flag = '1'; break;
            default : $flag = '2'; break;
        }
        $this->db->trans_start();
        $isUpdate = $this->user_related_self->toggle($id, $flag);
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === TRUE && $isUpdate) {
            echo json_encode(array(
                'flag' => $flag,
            ));
        } else {
            echo json_encode(array(
                'flag' => 3,
            ));
        }
        exit;
    }
    
     /**
     *检查供应商是否重复
     */
    public function checkProviderRepeat(){
         
        $provider_uid = trim( $this->input->get('provider_uid') );
        $id = trim( $this->input->get('id') );
        $result = $this->user_related_self->providerUidRepeat($provider_uid);
        if( empty($id) ){  // 添加
            echo ( $result->num_rows() > 0 ) ? "false" : "true" ; exit;
        }else{ //修改
            echo ( $result->num_rows() > 0 && $result->row(0)->id != $id ) ? "false" : "true";exit;
        }
    }
    
     /**
     * 添加分润
     * @param unknown $id
     */
    public function addprofit($id){
        
        $usereLated = $this->user_related_self->findById($id);
        if( $usereLated->num_rows() <= 0 ){
            $this->error('userrelatedself/grid', '', '查询失败');
        }
        $data['usereLated'] = $usereLated->row(0);
        $data['poundageProfit'] = $this->provider_poundage_profit->getProviderResultByRelatedId($id);
        $data['userType'] = $this->user_type->get_list('Y', array('8192', '134217728')); //用户分润
        $data['id'] = $id;
        $this->load->view('userrelatedself/addprofit',$data);
    }
    
    public function ajaxValidate()
    {
        $error = $this->validateProfit();
        $param = $this->input->post();
        if (!empty($error)) {
            $this->jsen($error);
        }
        if ($param['solve_type'] == 1) {
            $this->editProviderProfitPost($param);
        } else {
            $this->addProviderProfitPost($param);
        }
    }
    
    public function addProviderProfitPost($param){
    	
        $this->db->trans_start();
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($param)));
        $resultId = $this->provider_poundage_profit->add($param);
        $this->db->trans_complete();
        if($this->db->trans_status() === false){
        	$this->jsen('数据库插入失败');
        } else{
            $this->session->set_flashdata('success', '保存成功!');
            $this->jsen(base_url('userrelatedself/grid'), TRUE);
        }
    }
    
    public function editProviderProfitPost($param){
    	
        $this->db->trans_start();
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($param)));
        $this->provider_poundage_profit->deleteByRelatedId($param['user_related_id']);
        $resultId = $this->provider_poundage_profit->add($param);
        $this->db->trans_complete();
        if($this->db->trans_status() === false){
            $this->jsen('数据库插入失败');
        } else{
            $this->session->set_flashdata('success', '保存成功!');
            $this->jsen(base_url('userrelatedself/grid'), TRUE);
        }
    }
    
    public function validateProfit()
    {
        $error = array();
        $typeIDArray = $this->input->post('type_id');
        $uidArray = $this->input->post('uid');
        $poundageArray = $this->input->post('poundage');
        $amount = 0;        //手续费金额
        if(empty($uidArray) || empty($typeIDArray) || empty($poundageArray)){
            return $error[] = '请仔细核对，手续费，分润金额！';
        }
        //去掉为空  的用户uid
        foreach ($uidArray as $key => $value) {
            if (empty($value)) {
                unset($uidArray[$key]);
            }
        }
        if (count($uidArray) != count($typeIDArray) || count($uidArray) != count($poundageArray)) {
            return $error[] = '请请仔细核对数据，插入数组长度不一样';
        }
        foreach ($typeIDArray as $key => $value) {
            if (!is_numeric($poundageArray[$key]) || $poundageArray[$key] < 0) {
                return $error[] = '手续费必须填写大于或等于0的数字！';
            }
            $amount += $poundageArray[$key];
        }
        if (bccomp($amount,100,3) != 0) {
            return $error[] = '手续费总额不等于100';
        }
        $result = $this->user->findByIds(array('uid' => $uidArray));
        if (empty($result)) {
            return $error[] = '用户编号为' . implode(array_flip($uidArray), ',') . '的用户不存';
        }
        $uidArray = array_flip($uidArray);   //  key值交换
        foreach ($result->result() as $value) {
            
            if (array_key_exists($value->uid, $uidArray)) {
                unset($uidArray[$value->uid]);
            }
        }
        if (!empty($uidArray)) {
            return $error[] = '用户UID为' . implode(array_flip($uidArray), ',') . '的用户不存在';
        }
        return $error;
    }
    
    private function jsen($error, $flag = false)
    {
        echo json_encode(array(
                'status'   => $flag,
                'messages' => $error
        ));
        exit;
    }
}